from django.db import models
from django.core.exceptions import ValidationError
from django.utils import timezone
from datetime import timedelta, date  # 添加此导入解决 timedelta 和 date 引用问题
from django.core.validators import MaxValueValidator, MinValueValidator  # 添加此导入解决验证器引用问题

from utills.validators import validate_license_plate

class BusModel(models.Model):
    name = models.CharField('车型名称', max_length=20, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '车型'
        verbose_name_plural = '车型管理'
class Bus(models.Model):
    BUS_STATUS = [('normal', '正常'), ('maintenance', '维修')]

    bus_id = models.CharField(
        '车牌号',
        max_length=10,
        primary_key=True,
        validators=[validate_license_plate]  # 添加自定义验证器
    )
    model = models.ForeignKey(BusModel, on_delete=models.PROTECT, verbose_name='车型')
    capacity = models.IntegerField(
        '核载人数',
        validators=[
            MaxValueValidator(60, message="请输入30-60之间的数"),
            MinValueValidator(30, message="请输入30-60之间的数")
        ]
    )
    status = models.CharField('状态', max_length=20, choices=BUS_STATUS, default='normal')

    def __str__(self):
        return f"{self.bus_id} ({self.model})"

    def unique_error_message(self, model_class, unique_check):
        # 自定义唯一性冲突的错误提示
        if model_class == Bus and unique_check == ('bus_id',):
            return '该车牌号已存在，请输入不同的车牌号。'
        return super().unique_error_message(model_class, unique_check)

class Driver(models.Model):
    DRIVER_STATUS = [('on_duty', '在岗'), ('off_duty', '休假')]
    LICENSE_TYPE = [('A1', 'A1'), ('A3', 'A3')]

    driver_id = models.CharField('工号', max_length=8, primary_key=True)
    name = models.CharField('姓名', max_length=10)
    license = models.CharField('驾照类型', max_length=2, choices=LICENSE_TYPE)
    status = models.CharField('状态', max_length=20, choices=DRIVER_STATUS, default='on_duty')

    def __str__(self):
        return f"{self.driver_id} - {self.name}"


class Schedule(models.Model):
    schedule_id = models.AutoField('排班ID', primary_key=True)
    departure_time = models.DateTimeField('发车时间')
    bus = models.ForeignKey(Bus, on_delete=models.CASCADE, verbose_name='车辆')
    driver = models.ForeignKey(Driver, on_delete=models.CASCADE, verbose_name='司机')

    class Meta:
        ordering = ['-departure_time']

    def clean(self):
        # 班次冲突检测
        overlapping_schedules = Schedule.objects.filter(
            bus=self.bus,
            departure_time__range=(
                self.departure_time - timedelta(minutes=30),
                self.departure_time + timedelta(minutes=30)
            )
        ).exclude(pk=self.pk)

        if overlapping_schedules.exists():
            raise ValidationError("同一车辆30分钟内不可排多个班次")

        overlapping_driver = Schedule.objects.filter(
            driver=self.driver,
            departure_time__range=(
                self.departure_time - timedelta(minutes=60),
                self.departure_time + timedelta(minutes=60)
            )
        ).exclude(pk=self.pk)

        if overlapping_driver.exists():
            raise ValidationError("同一司机60分钟内不可排多个班次")

        # 维修车辆检查
        if self.bus.status == 'maintenance':
            raise ValidationError("维修车辆不可排班")

        # 休假司机检查
        if self.driver.status == 'off_duty':
            raise ValidationError("休假司机不可排班")


class Maintenance(models.Model):
    bus = models.ForeignKey(Bus, on_delete=models.CASCADE, verbose_name='车辆')
    start_date = models.DateField('开始日期', default=timezone.now)
    end_date = models.DateField('结束日期', null=True, blank=True)
    reason = models.CharField('维修原因', max_length=100)

    @property
    def duration(self):
        end = self.end_date or date.today()  # 修复 date 引用
        return (end - self.start_date).days


class Admin(models.Model):
    """管理员表"""
    username = models.CharField(verbose_name='用户名', max_length=32)
    password = models.CharField(verbose_name='密码', max_length=100)
    captcha = models.CharField(verbose_name='验证码', max_length=32, null=True, blank=True)
    objects = models.Manager()  # 必须存在这一行